<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
      >
      </el-alert>
      <!-- 选择分类 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择框 -->
          <el-cascader
            v-model="cascaderKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs组件 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            class="cat_opt"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 表格区 -->
          <el-table :data="manybutesList" style="width: 100%" border stripe>
            <el-table-column type="expand">
              <template v-slot="scoped">
                <!-- 循环渲染tag表现 -->
                <el-tag
                  v-for="(item, i) in scoped.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scoped.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scoped.row.inputVisible"
                  v-model="scoped.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scoped.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="分类参数">
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="sonped">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editFn(sonped.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteFn(sonped.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 表格区 -->
          <el-table :data="onlybutesList" style="width: 100%" border stripe>
            <el-table-column type="expand">
              <template v-slot="scoped">
                <!-- 循环渲染tag表现 -->
                <el-tag
                  v-for="(item, i) in scoped.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scoped.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scoped.row.inputVisible"
                  v-model="scoped.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scoped.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="静态属性">
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="sonped">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editFn(sonped.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteFn(sonped.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="`添加${titleText}`"
      :visible.sync="addDialogVisible"
      width="70%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addRuleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveaddDialogFn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数的对话框 -->
    <el-dialog
      :title="`修改${titleText}`"
      :visible.sync="editDialogVisible"
      width="70%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editRules"
        ref="editRuleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditDialogFn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品列表
      cateList: [],
      //   级联选择器的配置项
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      //   保存选中的ID
      cascaderKeys: [],
      //被激活的页签名称
      activeName: "many",
      //参数列表
      manybutesList: [],
      onlybutesList: [],
      //   显示与隐藏添加对话框
      addDialogVisible: false,
      addForm: {
        attr_name: "",
      },
      addRules: {
        attr_name: [{ required: true, message: "请输入参数", trigger: "blur" }],
      },
      //   修改的显示与隐藏对话框
      editDialogVisible: false,
      // 保存修改的对象
      editForm: {
        cat_name: "",
      },
      //   修改规则
      editRules: {
        attr_name: [{ required: true, message: "请输入参数", trigger: "blur" }],
      },
      //   //控制按钮与文本框的切换显示
      //   inputVisible: false,
      //   //   文本输入的内容
      //   inputValue: "",
    };
  },
  created() {
    this.getCate();
  },
  methods: {
    /* 获取商品分类 */
    async getCate() {
      const { data: res } = await this.$axios.get("categories");
      if (res.meta.status !== 200)
        return this.$message.error("获取商品列表失败");
      this.cateList = res.data;
      //   console.log(this.cateList);
    },
    // 级联选择器的change事件
    handleChange() {
      this.getParamsData();
    },

    // tab标签点击事件的处理函数
    handleTabClick() {
      this.getParamsData();
    },
    // 获取分类参数列表
    async getParamsData() {
      //判断cascaderKeys的数组长度，如果不等于3 则不是三级分类，数组清空
      if (this.cascaderKeys.length !== 3) {
        this.cascaderKeys = [];
        this.onlybutesList = [];
        this.manybutesList = [];
        return;
      }
      //   console.log(this.cascaderKeys);
      /* 根据所选的id，所选的面板，获取分类参数列表 */
      const { data: res } = await this.$axios.get(
        `categories/${this.cateID}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      if (res.meta.status !== 200)
        return this.$message.error("获取参数列表失败");

      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // 控制文本框的显示与隐藏
        item.inputVisible = false;
        item.inputValue = "";
      });
      // 判断当前的面板是那个，并将值赋值给对象的数组中
      if (this.activeName === "many") {
        this.manybutesList = res.data;
      } else {
        this.onlybutesList = res.data;
      }
      console.log(res.data);
    },
    // 添加参数对话框关闭
    addDialogClosed() {
      this.$refs.addRuleForm.resetFields();
    },
    // 添加属性
    saveaddDialogFn() {
      this.$refs.addRuleForm.validate(async (valid) => {
        if (!valid) return this.$message.error("数据不合法");
        const { data: res } = await this.$axios.post(
          `categories/${this.cateID}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 201)
          return this.$message.error("添加参数分类失败");
        this.getParamsData();
        this.$message.success("添加参数成功");
        this.addDialogVisible = false;
      });
    },
    // 编辑确定 根据id修改参数
    saveEditDialogFn() {
      this.$refs.editRuleForm.validate(async (valid) => {
        if (!valid) return this.$message.error("数据不合法");
        const { data: res } = await this.$axios.put(
          `categories/${this.cateID}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        );
        if (res.meta.status !== 200) return this.$message.error("修改数据失败");
        this.$message.success("修改数据成功");
        this.getParamsData();
        this.editDialogVisible = false;
      });
    },
    // 修改对话框关闭表单重置
    editDialogClosed() {
      this.$refs.editRuleForm.resetFields();
    },
    // 根据ID查询参数
    async editFn(attr_id) {
      const { data: res } = await this.$axios.get(
        `categories/${this.cateID}/attributes/${attr_id}`,
        { params: { attr_sel: this.activeName } }
      );
      if (res.meta.status !== 200) return this.$message.error("查询失败");
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    // 根据id删除
    async deleteFn(attr_id) {
      /* 判断用户是否想要删除数据 */
      const res = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      //   console.log(res);
      if (res !== "confirm") return this.$message.info("你取消了删除操作");
      // 调接口发送删除请求
      const { data: res1 } = await this.$axios.delete(
        `categories/${this.cateID}/attributes/${attr_id}`
      );
      if (res1.meta.status !== 200) return this.$message.error("删除失败");
      this.$message.success("删除成功");
      this.getParamsData();
    },
    // 文本框失去焦点或enter键
    handleInputConfirm(row) {
    //   console.log(row.inputValue);
      /* 判断文本框有没有值，没有值，则 inputVisible = false */
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false;
        row.inputValue = "";
        return;
      }
      //   console.log("ok");
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      /* 发起请求保存参数 */
      this.getAttrVals(row);
    },
    // 保存参数
    async getAttrVals(row) {
      const { data: res } = await this.$axios.put(
        `categories/${this.cateID}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.meta.status !== 200) return this.$message.error("添加失败");
      this.$message.success("添加成功");
    },
    // 点击按钮展示文本输入逛
    showInput(Inp) {
      Inp.inputVisible = true;
      /* 让文本框自动获得焦点 

        $nextTick 页面元素重新渲染之后，才会回调函数
      
      */
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleClose(i, row) {
      row.attr_vals.splice(i, 1);
      this.getAttrVals(row);
    },
  },
  computed: {
    /* 如果 cascaderKeys的长度等于 3 则启用 ，反之，禁用*/
    isBtnDisabled() {
      if (this.cascaderKeys.length !== 3) return true;
      return false;
    },
    // 当前选中的三级ID
    cateID() {
      if (this.cascaderKeys.length !== 3) return null;
      return this.cascaderKeys[2];
    },
    // 添加对话框 == 公共
    titleText() {
      if (this.activeName === "many") return "动态参数";
      return "静态属性";
    },
  },
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 0.25rem 0;
}
.el-tag {
  margin: 20px;
}
.input-new-tag {
  width: 120px;
}
.el-button--small,
.el-input {
  margin: 20px;
}
</style>